package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"gitee.com/winnie_gss/MessageBox/logs"
	"os"
	"gopkg.in/ini.v1"
)

var client *redis.Client

type RedisConfig struct {
	RdHost     string
	RdPort     string
	RdPassword string
}

func InitRedis() {

	var redisConfig RedisConfig

	pwd, _ := os.Getwd()
	pwd += "\\.."
	file, err := ini.Load(pwd + "\\config.ini")
	logs.ErrorLog(err)

	file.BlockMode = false
	err = file.Section("redis").MapTo(&redisConfig)
	logs.ErrorLog(err)

	client = redis.NewClient(&redis.Options{Addr: fmt.Sprintf("%s:%s", redisConfig.RdHost, redisConfig.RdPort), Password: redisConfig.RdPassword})
	client.WrapProcess(func(old func(cmd redis.Cmder) error) func(cmd redis.Cmder) error {
		return func(cmd redis.Cmder) error {
			logs.InfoLog(fmt.Sprintf("starting process:<%s>\n", cmd))
			err := old(cmd)
			logs.InfoLog(fmt.Sprintf("finished process:<%s>\n", cmd))
			return err
		}
	})
}

func RGet(key string) *redis.StringCmd {
	cmd := redis.NewStringCmd("get", key)
	client.Process(cmd)
	return cmd
}

func RSet(key string, value interface{}) *redis.StringCmd {
	cmd := redis.NewStringCmd("set", key, value)
	client.Process(cmd)
	return cmd
}

func RExpire(key string, time int) *redis.StringCmd {
	cmd := redis.NewStringCmd("expire", key, time)
	client.Process(cmd)
	return cmd
}
